package tools

import (
	"fmt"
	"os"
	"strings"

	"github.com/shirou/gopsutil/process"
)

func (t Command) Ps() {

	if len(os.Args) != 3 {
		fmt.Println("请求参数有误！请参考：yt ps {name}")
		return
	}
	processName := os.Args[2]

	pids, pnames, err := getPIDsByProcessName(processName)
	if err != nil {
		fmt.Printf("获取进程 ID 时出错: %v\n", err)
		return
	}
	if len(pids) == 0 {
		fmt.Printf("未找到名为 %s 的进程\n", processName)
	} else {
		for i, pid := range pids {
			fmt.Printf("找到进程 %s，进程ID: %d,进程name: %s\n", processName, pid, pnames[i])
		}
	}
}

// getPIDsByProcessName 根据进程名获取对应的进程 ID 列表
func getPIDsByProcessName(name string) ([]int32, []string, error) {
	var pids []int32
	var pnames []string
	processes, err := process.Processes()
	if err != nil {
		return nil, nil, err
	}
	for _, p := range processes {
		procName, err := p.Name()
		if err == nil && strings.Contains(strings.ToLower(procName), strings.ToLower(name)) {
			pids = append(pids, p.Pid)
			pnames = append(pnames, procName)
		}
	}
	return pids, pnames, nil
}
